﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;

public partial class CreateProject : System.Web.UI.Page
{
    private static List<View> lViews;
    private static string path = "";
    private static int projectId = 0;
    private static string _division = "";
    private static int viewState;
    private static string _originalEducation;
    private static SubEducationBLL seBll = new SubEducationBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            viewState = 0;
            path = HttpContext.Current.Request.Url.AbsoluteUri;
            requirementField.Visible = false;
            TitelFinder();
            calStart.SelectedDate = DateTime.Today;
            calEnd.SelectedDate = DateTime.Today;
            hfAmount.Value = Convert.ToString(1);

            if (Divergence().Equals("1"))
            {
                if (_division == "Business" || _division == "Technology")
                {
                    lblDivergent.Text = "Virksomhedens navn";
                }
                else
                {
                    lblDivergent.Text = "Institutions navn";
                }
            }
            else
            {
                HttpCookie cookie = Request.Cookies["loginCookie"];
                lblDivergent.Text = "Uddannelse";
                txtDivergent.Enabled = false;
                string educationName = seBll.GetSubEducationNameByStudentID(cookie.Values["LoginId"]) + " - " + cookie.Values["LoginTerm"];
                _originalEducation = educationName;
                if (educationName.Length > 29)
                {
                    educationName = educationName.Remove(25);
                    educationName += "...";
                    txtDivergent.ToolTip = _originalEducation;
                }
                txtDivergent.Text = educationName;
                txtContactName.Text = cookie.Values["LoginName"];
                txtContactName.Enabled = false;
                txtEmail.Text = cookie.Values["LoginMail"];
                txtPhoneNo.Text = cookie.Values["LoginPhone"];
                sliderRanger.Visible = false;
                lblProject.Text = "Overskrift";
            }
        }
    }

    private void TitelFinder()
    {
        _division = path.Substring(path.LastIndexOf('/') + 1);
        //string result = "<b>Område:</b> "; ud kommenteret for test
        string result = "";
        switch (_division)
        {
            case "Business": result += "Business";  break;
            case "Pedagogue": result += "Pædagogik"; break;
            case "Interdisciplinary": result += "Tværfagligt"; break;
            case "HealthEducation": result += "Sundhed"; break;
            case "Technology": result += "Teknologi"; requirementField.Visible = true; break;

            default: result = "Er du gået forkert?"; break;
        }
        TextBox txtdiv = txtDivisionName;//test 
        if (_division.Equals("Interdisciplinary"))
        {
            indexWrapper.Visible = true;
        }
        txtDivisionName.Text = result;
    }

    private string Divergence()
    {
        return path.Substring(path.LastIndexOf('?') + 1, 1);
    }

    protected void btnGoToFront_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }

    protected void btnDone_Click(object sender, EventArgs e)
    {
        InsertProject();
    }

    protected void btnBackward_Click(object sender, EventArgs e)
    {
        if (viewState == 0)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "goBack", "history.go(-2);", true);
        }
        else
        {
            viewState--;
            mvCreate.ActiveViewIndex = viewState;
        }
    }

    protected void btnForward_Click(object sender, EventArgs e)
    {
        if (InfoInsertCheck())
        {
            viewState++;
            if (lViews.Count > viewState)
            {
                mvCreate.ActiveViewIndex = viewState;

                if (lViews.Count - 1 == viewState)
                {
                    btnForward.Text = "Opret";
                }
                else
                {
                    btnForward.Text = "Videre";
                }
            }
            else if (lViews.Count == viewState)
            {
                if (InsertProject())
                {
                    HttpCookie cookie = new HttpCookie("CookieProject");
                    cookie.Values.Add("CookieProjectID", projectId.ToString());
                    cookie.Values.Add("CookieProjectMail", txtEmail.Text);
                    cookie.Values.Add("CookieProjectDivision", _division);
                    cookie.Expires = DateTime.Now.AddMinutes(60);

                    Response.Cookies.Add(cookie);
                    viewState = 0;
                    Response.Redirect("~/ThankPage.aspx");
                }
            }
        }
    }

    protected void calStart_SelectionChanged(object sender, EventArgs e)
    {

    }

    protected void calEnd_SelectionChanged(object sender, EventArgs e)
    {

    }

    private bool InfoInsertCheck()
    {
        bool canDo = true;
        string fault = "<a style='color:red;'>*</a>";

        if (String.IsNullOrEmpty(txtProjectTitel.Text))
        {
            canDo = false;
            txtProjectTitel.CssClass = "txtProjectError";
        }
        if (String.IsNullOrEmpty(txtContactName.Text))
        {
            canDo = false;
            txtContactName.CssClass = "txtProjectError";
        }
        if (String.IsNullOrEmpty(txtDivergent.Text))
        {
            canDo = false;
            txtDivergent.CssClass = "txtProjectError";
        }
        if (String.IsNullOrEmpty(txtEmail.Text))
        {
            canDo = false;
            txtEmail.CssClass = "txtProjectError";
        }

        if (calStart.SelectedDate < calEnd.SelectedDate && calStart.SelectedDate >= DateTime.Today)
        {
        }
        else
        {
            canDo = false;
            lblStart.Text += fault;
        }
        if (calEnd.SelectedDate > calStart.SelectedDate && calEnd.SelectedDate > DateTime.Today)
        {
        }
        else
        {
            canDo = false;
            lblEnd.Text += fault;
        }
        if (!canDo)
        {
            //lblStatus.Text = "* Er ikke udfyldt korrekt";
        }
        return canDo;
    }

    private bool InsertProject()
    {
        bool canDo = true;
        ProjectProberty pp = new ProjectProberty();
        ProjectBLL pBll = new ProjectBLL();
        AnswerBLL aBll = new AnswerBLL();
        AnswerProperty aPro = new AnswerProperty();
        InterdisciplinaryBLL iBll = new InterdisciplinaryBLL();
        pp.Title = txtProjectTitel.Text;
        pp.ContactName = txtContactName.Text;
        pp.CompanyName = txtDivergent.Text;
        pp.Email = txtEmail.Text;
        pp.StartPeriod = calStart.SelectedDate;
        pp.EndPeriod = calEnd.SelectedDate;
        pp.PhoneNo = txtPhoneNo.Text;
        pp.Requirements = "blank";
        pp.Reserved = false;
        pp.TimesReserved = Convert.ToInt32(hfAmount.Value);
        pp.LifeSpan = calEnd.SelectedDate;


        if (Divergence().Equals("1"))
        {
            if (!String.IsNullOrEmpty(_division))
            {
                string result = "";
                switch (_division)
                {
                    case "Business": result = "Business"; break;
                    case "Pedagogue": result = "Pædagogik"; break;
                    case "Interdisciplinary": result = "Tværfagligt"; break;
                    case "HealthEducation": result = "Sundhed"; break;
                    case "Technology": result = "Teknologi"; break;
                }
                DivisionBLL dBll = new DivisionBLL();
                DivisonProperty dPP = new DivisonProperty();
                dPP = dBll.GetDivisionByName(result);
                pp.DivisionId = dPP.Id;
            }
            if (pBll.CreateProjectCompany(pp) > 0)
            {
                projectId = pBll.MaxProjectID();

                for (int i = 0; i < lViews.Count - 1; i++)
                {
                    TextBox txtAns = (TextBox)lViews[i].FindControl("txtAnsw" + i) as TextBox;
                    HiddenField hfQId = (HiddenField)lViews[i].FindControl("hfQuestId" + i) as HiddenField;
                    aPro.AnsAnswer = txtAns.Text;
                    aPro.QuestionId = Convert.ToInt32(hfQId.Value);
                    aPro.ProjectId = projectId;
                    aBll.InsertAnswer(aPro);
                }
            }
            else
            {
                canDo = false;
                lblStatus.Text = "Der var et problem med databasen";
            }
        }
        else if (Divergence().Equals("2"))
        {
            if (!String.IsNullOrEmpty(_division))
            {
                string result = "";
                switch (_division)
                {
                    case "Business": result = "Business"; break;
                    case "Pedagogue": result = "Pædagogik"; break;
                    case "Interdisciplinary": result = "Tværfagligt"; break;
                    case "HealthEducation": result = "Sundhed"; break;
                    case "Technology": result = "Teknologi"; break;
                }
                DivisionBLL dBll = new DivisionBLL();
                DivisonProperty dPP = new DivisonProperty();
                dPP = dBll.GetDivisionByName(result);
                pp.DivisionId = dPP.Id;
            }
            pp.SubEducationId = Convert.ToInt32(Request.Cookies["loginCookie"].Values["LoginEduc"]);
            if (pBll.CreateProjectStudent(pp) > 0)
            {
                projectId = pBll.MaxProjectID();

                for (int i = 0; i < lViews.Count - 1; i++)
                {
                    TextBox txtAns = (TextBox)lViews[i].FindControl("txtAnsw" + i) as TextBox;
                    HiddenField hfQId = (HiddenField)lViews[i].FindControl("hfQuestId" + i) as HiddenField;
                    aPro.AnsAnswer = txtAns.Text;
                    aPro.QuestionId = Convert.ToInt32(hfQId.Value);
                    aPro.ProjectId = projectId;
                    aBll.InsertAnswer(aPro);
                }
            }
            else
            {
                canDo = false;
                lblStatus.Text = "Der var et problem med databasen";
            }
        }
        if (_division.Equals("Interdisciplinary"))
        {
            foreach (ListItem item in cblDivisions.Items)
            {
                if (item.Selected)
                {
                    if (iBll.CreateInterdiscipinaryLink(projectId, Convert.ToInt32(item.Value)) < 0)
                    {
                        canDo = false;
                    }
                }
            }
        }
        return canDo;
    }

    private void GenerateView(int viewId, QuestionProperty q)
    {
        View v = new View();
        v.ID = "newView" + viewId;


        HtmlGenericControl divOuter = new HtmlGenericControl("div");
        divOuter.Attributes["class"] = "qCenterization";

        HtmlGenericControl divInner = new HtmlGenericControl("div");
        divInner.Attributes["class"] = "center";
        
        Label qil = new Label();
        qil.Attributes["class"] = "lblQInfo";
        qil.Text = "Dette spørgsmål hjælper dig med at udforme den fulde projektbeskrivelse<br/><br/><br/>";

        
        Label nl = new Label();
        nl.Attributes["class"] = "txtQuestion";
        nl.Text = q.QueQuestion;

        TextBox tb = new TextBox();
        tb.Attributes["class"] = "txtAnswer";
        tb.ID = "txtAnsw" + viewId;
        tb.TextMode = TextBoxMode.MultiLine;
        tb.Attributes["placeholder"] = q.QuePlaceholder;

        HiddenField hfId = new HiddenField();
        hfId.ID = "hfQuestId" + viewId;
        hfId.Value = q.Id.ToString();

        divOuter.Controls.Add(qil);
        divOuter.Controls.Add(nl);
        
        divInner.Controls.Add(tb);
        divInner.Controls.Add(hfId);
        divOuter.Controls.Add(divInner);
        v.Controls.Add(divOuter);

        lViews.Add(v);
        mvCreate.Views.Add(v);
    }

    protected void Page_OnPreInit(object sender, EventArgs e)
    {
        PreInit += new EventHandler(Page_OnPreInit);
        Load += new EventHandler(Page_Load);
        Init += new EventHandler(Page_Init);
        base.OnPreInit(e);
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        // Check if postback
        if (Page.IsPostBack)
        {
            lViews = new List<View>();
            Dictionary<int, QuestionProperty> qDic = Questions();
            foreach (View v in mvCreate.Views)
            {
                lViews.Add(v);
            }
            for (int i = 0; i < qDic.Count; i++)
            {
                GenerateView(i, qDic[i]);
            }
        }
    }

    private Dictionary<int, QuestionProperty> Questions()
    {
        QuestionBLL qBll = new QuestionBLL();
        QuestionProperty qp = new QuestionProperty();
        DivisionBLL dBll = new DivisionBLL();
        Dictionary<int, QuestionProperty> qDic = new Dictionary<int, QuestionProperty>();

        string result = "";
        switch (_division)
        {
            case "Business": result = "Business"; break;
            case "Pedagogue": result = "Pædagogik"; break;
            case "Interdisciplinary": result = "Tværfagligt"; break;
            case "HealthEducation": result = "Sundhed"; break;
            case "Technology": result = "Teknologi"; break;
        }
        bool IsForStudent = false;
        if (Divergence().Equals("2"))
        {
            IsForStudent = true;
        }
        List<QuestionProperty> qList = qBll.GetAllQuestionsByDivision(dBll.GetDivisionByName(result).Id, IsForStudent);
        for (int i = 0; i < qList.Count; i++)
        {
            qp = qList[i];
            qDic.Add(i, qp);
        }

        return qDic;
    }
}